package com.ironmaking.Service.impl;

import com.ironmaking.DAO.IngotRateDataDAO;
import com.ironmaking.DAO.IngotRateTableDAO;
import com.ironmaking.Entity.IngotRateData;
import com.ironmaking.Entity.IngotRateTable;
import com.ironmaking.Entity.YieldRateData;
import com.ironmaking.Entity.YieldRateTable;
import com.ironmaking.Service.Interface.IIngotRateService;
import com.ironmaking.Utils.PageUtil;
import com.ironmaking.Vo.data.IngotRateTableRowData;
import com.ironmaking.Vo.results.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IngotRateService implements IIngotRateService {

    @Autowired
    IngotRateDataDAO ingotRateDataDao;

    @Autowired
    IngotRateTableDAO ingotRateTableDAO;

    @Override
    public PageResult getIngotTableByYid(int iid, int page, int size) {
        Specification<IngotRateData> specification = (Specification<IngotRateData>)
                (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("Iid"), iid);
        return PageUtil.toPageResult(page,size,ingotRateDataDao.findAll(specification));
    }

    @Override
    public int uploadingIngotTable(int uid, String tableName, List<IngotRateTableRowData> ingotRateDataTable) {
        IngotRateTable ingotRateTable = new IngotRateTable();
        ingotRateTable.setUpdateUserId(uid);
        ingotRateTable.setTableName(tableName);
        ingotRateTable.setUploadTime(new Date().getTime());
        try {
            ingotRateTable = ingotRateTableDAO.save(ingotRateTable);
            int Iid = ingotRateTable.getIngotDataId();
            List<IngotRateData> ingotRateDateList = new ArrayList();
            for (IngotRateTableRowData ingotRateTableRowData : ingotRateDataTable) {
                ingotRateDateList.add(new IngotRateData().insertPropFromRowData(Iid,ingotRateTableRowData));
            }
            ingotRateDataDao.saveAll(ingotRateDateList);
            return Iid;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
    }
}
